package com.xinzhi.controller;

import com.xinzhi.pojo.LoanInterest;
import com.xinzhi.service.impl.LoanInterestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 处理贷款利息相关请求的控制器。
 */
@RestController
@RequestMapping("/loan/interest")
public class LoanInterestController {

    @Autowired
    private LoanInterestService loanInterestService;

    /**
     * 获取所有贷款利息记录。
     *
     * @return 所有贷款利息记录的列表
     */
    @GetMapping("/all")
    public List<LoanInterest> getAllLoanInterests() {
        return loanInterestService.getLoanInterestsByLoanAccount(null);
    }

    /**
     * 根据贷款账号获取贷款利息记录。
     *
     * @param loanAccount 贷款账号
     * @return 对应贷款账号的贷款利息记录列表
     */
    @GetMapping("/{loanAccount}")
    public List<LoanInterest> getLoanInterestsByLoanAccount(@PathVariable String loanAccount) {
        return loanInterestService.getLoanInterestsByLoanAccount(loanAccount);
    }

    /**
     * 计算并保存贷款利息记录。
     *
     * @param loanAccount        贷款账号
     * @param loanBalance        贷款余额
     * @param interestStartDate  利息开始日期
     * @param interestDueDate    利息到期日期
     * @param interestRate       利率
     * @return 表示操作结果的消息
     */
    @PostMapping("/calculate")
    public String calculateAndSaveLoanInterest(
            @RequestParam String loanAccount,
            @RequestParam BigDecimal loanBalance,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date interestStartDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date interestDueDate,
            @RequestParam float interestRate) {

        try {
            LoanInterest loanInterest = new LoanInterest();
            loanInterest.setLoanAccount(loanAccount);
            loanInterest.setLoanBalance(loanBalance);
            loanInterest.setInterestStartDate(interestStartDate);
            loanInterest.setInterestDueDate(interestDueDate);
            loanInterest.setInterestRate(interestRate);

            loanInterestService.calculateAndSaveLoanInterest(loanInterest);
            return "贷款利息计算并保存成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "计算和保存贷款利息失败: " + e.getMessage();
        }
    }
}
